package com.inwavetech.os.util;

import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;

import com.inwavetech.os.entity.Os;

import java.util.Collection;
import java.util.List;

/**
 * Created by jgskin on 2/2/14.
 */
public class OsSync {

    private final AuthenticatedRequest authenticatedRequest;
    private final syncProccessListenerInterface syncProccessListener;
    private final OsJsonParser osJsonParser;
    private final String getOsUrl;

    public OsSync(AuthenticatedRequest authenticatedRequest, OsJsonParser osJsonParser,
                  String getOsUrl, syncProccessListenerInterface syncProccessListener) {
        this.authenticatedRequest = authenticatedRequest;
        this.syncProccessListener = syncProccessListener;
        this.osJsonParser = osJsonParser;
        this.getOsUrl = getOsUrl;
    }

    public void sync() {
        new Sync().execute();
    }

    public interface syncProccessListenerInterface {
        public void onSyncException(Exception e);

        public void onSyncHttpError(SimpleResponse simpleResponse);

        public void onPostSync(Collection<Os> importedOses);
    }

    private class Sync extends AsyncTask<String, String, SimpleResponse> {

        @Override
        protected SimpleResponse doInBackground(String... params) {
            StrictMode.ThreadPolicy mThreadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(mThreadPolicy);

            return authenticatedRequest.get(getOsUrl);
        }

        @Override
        protected void onPostExecute(SimpleResponse response) {
            if (response != null && response.code == 200) {

                try {
                    List<Os> importedOses = osJsonParser.parse(response.body);

                    syncProccessListener.onPostSync(importedOses);
                } catch (OsJsonParser.Exception e) {
                    syncProccessListener.onSyncException(e);
                }

            } else {
                Log.e(OsSync.class.getName(), "No server response or wrong http code");

                syncProccessListener.onSyncHttpError(response);
            }

        }

    }

}
